//
// Created by Ukua on 2023/11/2.
//

#include "DR16.h"
// 遥控器数据
RC_ctrl_t *rc_ctrl;

DaemonInstance *g_rc_daemon_instance;

Bus_SubscriberTypeDef *g_dr16_rx;

Bus_TopicHandleTypeDef *g_dr16_signal_disconnected,//遥控器失联
*g_dr16_signal_connected,//遥控器连接
*g_dr16_signal_updated;//遥控器数据更新

uint8_t g_dr16_is_connected = 0;

uint32_t g_last_solve_tick = 0;

/**
 * @brief 矫正遥控器摇杆的值,超过660或者小于-660的值都认为是无效值,置0
 *
 */
static void RectifyRCjoystick()
{
    for (uint8_t i = 0; i < 5; ++i)
    {
        if (abs(*(&rc_ctrl[TEMP].rc.rocker_l_ + i)) > 660)
            *(&rc_ctrl[TEMP].rc.rocker_l_ + i) = 0;
    }
}

/**
 * @brief          remote control protocol resolution
 * @param[in]      sbus_buf: raw data point
 * @param[out]     rc_ctrl: remote control data struct point
 * @retval         none
 */

static void DR16_solve(const uint8_t *sbus_buf)
{

    // 遥控器连接signal
    if(!g_dr16_is_connected){
        g_dr16_is_connected = 1;
        Bus_Publish(g_dr16_signal_connected,NULL);
    }

    // 记录更新时间
    rc_ctrl[TEMP].update_time = HAL_GetTick();

    // 摇杆,直接解算时减去偏置
    rc_ctrl[TEMP].rc.rocker_r_ = ((sbus_buf[0] | (sbus_buf[1] << 8)) & 0x07ff) - RC_CH_VALUE_OFFSET;                              //!< Channel 0
    rc_ctrl[TEMP].rc.rocker_r1 = (((sbus_buf[1] >> 3) | (sbus_buf[2] << 5)) & 0x07ff) - RC_CH_VALUE_OFFSET;                       //!< Channel 1
    rc_ctrl[TEMP].rc.rocker_l_ = (((sbus_buf[2] >> 6) | (sbus_buf[3] << 2) | (sbus_buf[4] << 10)) & 0x07ff) - RC_CH_VALUE_OFFSET; //!< Channel 2
    rc_ctrl[TEMP].rc.rocker_l1 = (((sbus_buf[4] >> 1) | (sbus_buf[5] << 7)) & 0x07ff) - RC_CH_VALUE_OFFSET;                       //!< Channel 3
    rc_ctrl[TEMP].rc.dial = ((sbus_buf[16] | (sbus_buf[17] << 8)) & 0x07FF) - RC_CH_VALUE_OFFSET;                                 // 左侧拨轮
    RectifyRCjoystick();
    // 开关,0左1右
    rc_ctrl[TEMP].rc.switch_right = ((sbus_buf[5] >> 4) & 0x0003);     //!< Switch right
    rc_ctrl[TEMP].rc.switch_left = ((sbus_buf[5] >> 4) & 0x000C) >> 2; //!< Switch left

    // 鼠标解析
    rc_ctrl[TEMP].mouse.x = sbus_buf[6] | (sbus_buf[7] << 8);   //!< Mouse X axis
    rc_ctrl[TEMP].mouse.y = sbus_buf[8] | (sbus_buf[9] << 8);   //!< Mouse Y axis
    rc_ctrl[TEMP].mouse.z = sbus_buf[10] | (sbus_buf[11] << 8); //!< Mouse Z axis
    rc_ctrl[TEMP].mouse.press_l = sbus_buf[12];                 //!< Mouse Left Is Press ?
    rc_ctrl[TEMP].mouse.press_r = sbus_buf[13];                 //!< Mouse Right Is Press ?

    //  位域的按键值解算,直接memcpy即可,注意小端低字节在前,即lsb在第一位,msb在最后. 尚未测试
    *(uint16_t *)&rc_ctrl[TEMP].keyboard = (uint16_t)(sbus_buf[14] | (sbus_buf[15] << 8));

    // 发布遥控器数据更新signal
    Bus_Publish(g_dr16_signal_updated, NULL);

    DaemonReload(g_rc_daemon_instance); // 重载守护进程(检查遥控器是否正常工作

    memcpy(&rc_ctrl[1], &rc_ctrl[TEMP], sizeof(RC_ctrl_t)); // 保存上一次的数据,用于按键持续按下和切换的判断
}


void ET08_solve(const uint8_t *sbus_buf) {


    //为了强兼DR16,这里把ET08的通道数据解析成DR16的通道数据
    int16_t temp_rocker_r_ = (int16_t)((sbus_buf[1] | sbus_buf[2] << 8) & 0x07FF);
    int16_t temp_rocker_r1 = (int16_t)((sbus_buf[2] >> 3 | sbus_buf[3] << 5) & 0x07FF);
    temp_rocker_r_=(int16_t)(((float)temp_rocker_r_-1024.0f)/1341.0f*-660.0f*2.0f);
    temp_rocker_r1=(int16_t)(((float)temp_rocker_r1-1024.0f)/1341.0f*-660.0f*2.0f);

    int16_t temp_rocker_l1 = (int16_t)((sbus_buf[3] >> 6 | sbus_buf[4] << 2 | sbus_buf[5] << 10) & 0x07FF);
    int16_t temp_rocker_l_ = (int16_t)((sbus_buf[5] >> 1 | sbus_buf[6] << 7) & 0x07FF);
    temp_rocker_l1=(int16_t)(((float)temp_rocker_l1-1024.0f)/1341.0f*660.0f*2.0f);
    temp_rocker_l_=(int16_t)(((float)temp_rocker_l_-1024.0f)/1341.0f*660.0f*2.0f);

    //新遥控器断连逻辑有改变，因为新遥控器哪怕断连接收机也还是会发送消息，我们根据他断连后的特征（rocker_l_=-1006）决定是否喂狗
    if (temp_rocker_l1== -1006) {
        rc_ctrl[TEMP].rc.rocker_r_  = 0;
        rc_ctrl[TEMP].rc.rocker_r1  = 0;
        rc_ctrl[TEMP].rc.rocker_l_  = 0;
        rc_ctrl[TEMP].rc.rocker_l1  = 0;
        rc_ctrl[TEMP].rc.dial = 0;//防止意外修改
        return;

    }

    // 遥控器连接signal
    if(!g_dr16_is_connected){
        g_dr16_is_connected = 1;
        Bus_Publish(g_dr16_signal_connected,NULL);
    }

    // 记录更新时间
    rc_ctrl[TEMP].update_time = HAL_GetTick();

        int16_t temp_switch_left = (int16_t)((sbus_buf[6] >> 4 | sbus_buf[7] << 4) & 0x07FF);
    switch (temp_switch_left) {
        case 1024:
            rc_ctrl[TEMP].rc.switch_left = RC_SW_MID;
            break;
        case 353:
            rc_ctrl[TEMP].rc.switch_left = RC_SW_UP;
            break;
        case 1694:
            rc_ctrl[TEMP].rc.switch_left = RC_SW_DOWN;
            break;
        default:
            rc_ctrl[TEMP].rc.switch_left = 0;
            break;
    }

    int16_t temp_switch_right = (int16_t)((sbus_buf[7] >> 7 | sbus_buf[8] << 1 | sbus_buf[9] << 9) & 0x07FF);
    switch (temp_switch_right) {
        case 1024:
            rc_ctrl[TEMP].rc.switch_right = RC_SW_MID;
            break;
        case 353:
            rc_ctrl[TEMP].rc.switch_right = RC_SW_UP;
            break;
        case 1694:
            rc_ctrl[TEMP].rc.switch_right = RC_SW_DOWN;
            break;
        default:
            rc_ctrl[TEMP].rc.switch_right = 0;
            break;
    }



    rc_ctrl[TEMP].rc.rocker_r_  = -temp_rocker_r_;
    rc_ctrl[TEMP].rc.rocker_r1  = temp_rocker_r1;
    rc_ctrl[TEMP].rc.rocker_l_  = temp_rocker_l_;
    rc_ctrl[TEMP].rc.rocker_l1  = temp_rocker_l1;
    rc_ctrl[TEMP].rc.dial = 0;//防止意外修改
    rc_ctrl[TEMP].rc.custom_1  = (int16_t)((sbus_buf[9] >> 2 | sbus_buf[10] << 6) & 0x07FF);
    rc_ctrl[TEMP].rc.custom_2  = (int16_t)((sbus_buf[10] >> 5 | sbus_buf[11] << 3) & 0x07FF);
    RectifyRCjoystick();


    // 发布遥控器数据更新signal
        Bus_Publish(g_dr16_signal_updated, NULL);

        DaemonReload(g_rc_daemon_instance); // 重载守护进程(检查遥控器是否正常工作

        memcpy(&rc_ctrl[1], &rc_ctrl[TEMP], sizeof(RC_ctrl_t)); // 保存上一次的数据,用于按键持续按下和切换的判断




}

void DR16_RX_CallBack(void *message,Bus_TopicHandleTypeDef *topic){
    INTF_UART_MessageTypeDef *msg = (INTF_UART_MessageTypeDef *)message;
    if(msg->len == 18){
        DR16_solve(msg->data);
        g_last_solve_tick = HAL_GetTick();
    }
    if(msg->len == 25&&msg->data[0] == 0x0f){
        ET08_solve(msg->data);
        g_last_solve_tick = HAL_GetTick();
    }
}

void RCLostCallback(void *id){
    if(g_dr16_is_connected){
        g_dr16_is_connected = 0;
        Bus_Publish(g_dr16_signal_disconnected,NULL);
    }
}


void DR16_Init()
{
    rc_ctrl = Bus_SharePtr("DR16",sizeof(RC_ctrl_t)*2);

// 进行守护进程的注册,用于定时检查遥控器是否正常工作
    Daemon_Init_Config_s daemon_conf = {
            .reload_count = 100, // 100ms未收到数据视为离线,遥控器的接收频率实际上是1000/14Hz(大约70Hz)
            .callback = RCLostCallback,
            .owner_id = NULL, // 只有1个遥控器,不需要owner_id
    };
    g_rc_daemon_instance = DaemonRegister(&daemon_conf);


    g_dr16_rx = Bus_SubscribeFromName("/DBUS/RX",DR16_RX_CallBack);

    //遥控器事件
    g_dr16_signal_disconnected = Bus_TopicRegister("/signal/DR16/disconnected");
    g_dr16_signal_connected = Bus_TopicRegister("/signal/DR16/connected");
    g_dr16_signal_updated = Bus_TopicRegister("/signal/DR16/updated");

}
